<template>
  <view class="container screen-width">
    <view class="content">
      <van-uploader class="btn-box flex flex-center" accept="file" :maxCount="1" :before-read="beforeRead">
        <view class="btn">检测商业计划书</view>
      </van-uploader>
      <view class="tips">支持ppt、pptx、pdf格式文件检测，推荐pdf</view>

      <view class="file-text">文件上传进度</view>
      <van-progress :percentage="files.uploadPercentage" stroke-width="5" />
    </view>
    
    
    <van-popup v-model="showFile">
      <van-circle layer-color="#ebedf0" v-model="currentRate" :rate="rate" :speed="300" :text='`分析进度${rate}%`' />
    </van-popup>

    <view class="content-info">
      <image mode="widthFix" :src="$imgUrl + 'static/evaluation.png'" />
    </view>
  </view>
</template>
<script>
  import { isWeixin, wxShareConfig } from "@/util/wx.js";
  export default {
    data() {
      return {
        files: {
          uploadPercentage: 0
        },
        showFile: false,
        currentRate: 0,
        rate: 0,
        rateArr: []
      }
    },
    onLoad() {
     
    },
    onShow() {
      this.rate = 0
      var arr  = new Array(10).fill(0)
      for(var i=0;i<100;i++){
          var num = parseInt(Math.random()*10)
          arr[num] ++
      }
      this.rateArr = arr
      // this.showFile = false
      let token = this.$getToken()
      if (!token) {
        uni.showModal({
          title: '提示',
          content: '您还没有登录，请登录后操作！',
          cancelText: '取消', // 取消按钮的文字
          confirmText: '去登录', // 确认按钮文字
          confirmColor: '#1678ff',
          success: res => {
            if (res.confirm) {
              uni.setStorageSync('pageUrl', window.location.href)
              uni.navigateTo({
                url: '/pages/login/index',
              })
            } else {
              uni.switchTab({
                url: `/pages/index/index`,
              })
            }
          },
        })
      } 
      if (isWeixin()) {
        this.initShareConfig();
      }
    },
    onHide() {
      this.files.uploadPercentage = 0
      this.showFile = false
    },
    methods: {
      beforeRead(file) {
        if (file.size > 10 * 1024 * 1024) {
          uni.showToast({
            title: "文件大小不能超过10M",
            duration: 2000,
            icon: "none"
          });
          return
        }
        let formData = new FormData()
        formData.append('file', file, file.name)
        let params = formData.get('file')
        this.uploadFile(params).then(res=>{
          if(res.code === 200) {
            this.showFile = true
            var _this = this
            for(var i=0;i<this.rateArr.length;i++){
              (function (i) {
                setTimeout(function () {
                  _this.rate = _this.rate + _this.rateArr[i]
                  // console.log(_this.rate)
                  if(_this.rate == 100) {  
                    _this.currentRate = 0
                    _this.rate = 0
                    _this.rateArr = []
                    _this.showFile = false
                    setTimeout(()=>{
                      uni.navigateTo({
                        url: `/pages/business/detail/Index?id=${res.result}`,
                      })
                    })  
                    // console.log('文件分析弹窗',_this.showFile)
                  }
                }, 500 * i);
              })(i);
            }
          }else {
            uni.showToast({
              title: res.message,
              icon: "none"
            });
            this.files.uploadPercentage = 0
          }
        })
      },
      uploadFile(params) {
        // console.log(111111111111,this.files)
        var fileObj = this.files
        var p = new Promise(function (resolve, reject) {
          var _this = this
          // http://192.168.2.131:7002  https://bootapi.51bmj.cn
          var url = 'https://bootapi.51bmj.cn/bmj-api/api/cms/businessPlanEvaluation/evaluationBusinessPlan';
          var xhr = new XMLHttpRequest();
          xhr.open('POST', url, true);
          xhr.onload = function () {
            // 请求完成
            var data = JSON.parse(xhr.responseText);
            if (this.status === 200) {       
              if (data.success == true) {
                resolve(data);
              } else {
                resolve(data);
              }
            } else {
              resolve('上传失败');
            }
          };
          var formdata = new FormData();
          formdata.append('file', params);
          xhr.setRequestHeader('X-Access-Token', uni.getStorageSync("Mtoken"));

          xhr.upload.addEventListener('progress', function (e) {
            fileObj.uploadPercentage = Math.round((e.loaded * 100) / e.total); 
          }, false);
          // console.log(333333333,fileObj)
          xhr.send(formdata);
        });
        return p;
      },
      // 传入blob路径，.then()获取blob文件
      httpRequest(src) {
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest()
          xhr.open('GET', src, true)
          xhr.responseType = 'blob'
          xhr.onload = function (e) {
            if (this.status == 200) {
              let myBlob = this.response
              let files = new window.File([myBlob], myBlob.type, { type: myBlob.type })
              resolve(files)
            } else {
              reject(false)
            }
          }
          xhr.send()
        })
      },
      initShareConfig() {
        let _this = this;
        let windowurl = window.location.href.split("#")[0];
        uni.request({
          url: "https://oldm.51bmj.cn/WeiXin/GetClientSign", //仅为示例，并非真实接口地址。
          data: {
            rawUrl: windowurl
          },
          dataType: "json",
          header: {
            "X-Requested-With": "XMLHttpRequest"
          },
          method: "GET",
          success: res => {
            if (res.statusCode == 200) {
              let { data } = res;
              let shareInfo = {
                title: "商业计划书测评",
                desc: "任何一个人都可以用一份专业的商业计划书拉近公司和投资人的距离",
                link: window.location.href
              };
              // console.log(99999999, data, shareInfo);
              wxShareConfig(this.$wx, data, shareInfo);
            }
          }
        });
      }
    },
  }
</script>

<style lang="less" scoped>
  /deep/ .u-upload__wrap {
    justify-content: center;
  }
  /deep/.van-popup{
    padding: 40rpx;
    background: transparent;
  }
  /deep/.van-circle__text{
    color: #ffffff
  }
  .container {
    // padding: 30rpx;
    box-sizing: border-box;
    .content{
      padding: 30rpx;
      box-sizing: border-box;
    }
    .file-upload{
      font-size: 26rpx;
      background: #1678ff;
      color: #ffffff;
      width: 300rpx;
      text-align: center;
      height: 50rpx;
      line-height: 50rpx;
      border-radius: 20rpx;
      margin: 30rpx auto 0 auto;
      cursor: pointer;
    }
    .content-info {
      // padding-bottom: 50rpx;
      margin-top: 50rpx;
      image{
        width: 100%;
      }
      .title {
        font-size: 34rpx;
        font-weight: bold;
        text-align: center;
        height: 60rpx;
        line-height: 60rpx;
      }
      .info{
        font-size: 24rpx;
        line-height: 40rpx;
      }
    }
    .btn-box {
      width: 100%;
      .btn {
        font-size: 26rpx;
        background: #1678ff;
        color: #ffffff;
        width: 300rpx;
        text-align: center;
        height: 50rpx;
        line-height: 50rpx;
        border-radius: 20rpx;
      }
    }
    .tips {
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #bbbbbb;
      width: 100%;
      text-align: center;
      margin-bottom: 40rpx;
    }
    .file-text{
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #333333;
      width: 100%;
      margin-bottom: 20rpx;
    }
  }
</style>
